package com.pc.admin.strategy.strategyImpl;

import com.pc.admin.annotation.AutoFrequency;
import com.pc.admin.annotation.Limiting;
import com.pc.admin.entity.FrequencyEntity;
import com.pc.admin.strategy.FrequencyStrategy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * 限流IP 策略
 *
 * @author <a href="https://www.lvfeiy.top">lfy</a>
 * @date 2023/6/23 18:41
 */
@Component
@AutoFrequency
public class IpStrategy extends FrequencyStrategy {
    @Override
    public boolean analysis(Limiting.Target target) {
        return target.equals(Limiting.Target.IP);
    }

    @Override
    public FrequencyEntity service(Limiting limiting, ProceedingJoinPoint joinPoint) {
        return super.asbService(limiting, item -> {


            //获取ip、uri
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            assert requestAttributes != null;
            HttpServletRequest request = requestAttributes.getRequest();
            String uri = request.getRequestURI();
            String ip = super.getIpAddress(request);

            //key
            String key = "method_limit_".concat(uri).concat("_").concat(ip);

            item.setKey(key);

            return item;
        });

    }

    @Override
    public String getName() {
        return "根据IP进行限流";
    }
}
